package xyz.luhui1hao.springboottest.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private StringRedisTemplate template;

    @RequestMapping(value = "/setValue", method = RequestMethod.POST)
    public String setValue(@RequestParam(value = "key") String key, @RequestParam(value = "value") String value) {
            template.opsForValue().set(key, value);
            return "使用redis缓存保存数据成功";
    }

    @RequestMapping(value = "/getValue", method = RequestMethod.POST)
    public String getValue(@RequestParam(value = "key") String key) {

        if (!template.hasKey(key)) {
            return "key不存在，请先保存数据";
        } else {
            String value = template.opsForValue().get(key);//根据key获取缓存中的val
            return "获取到缓存中的数据：" + key + "=" + value;
        }
    }

    @RequestMapping(value = "/deleteValue", method = RequestMethod.POST)
    public String deleteValue(@RequestParam("key") String key){
        if (!template.hasKey(key)) {
            return "key不存在";
        }else {
            template.delete(key);
            return "删除成功";
        }
    }

}
